package com.huizu.project.controller;

import com.huizu.common.annotation.Anonymous;
import com.huizu.common.core.controller.BaseController;
import com.huizu.common.core.domain.AjaxResult;
import com.huizu.common.core.domain.entity.SysUser;
import com.huizu.common.core.page.TableDataInfo;
import com.huizu.common.utils.SecurityUtils;
import com.huizu.project.domain.SysUserAuth;
import com.huizu.project.domain.TheoryScoreVo;
import com.huizu.project.service.IProUserLlPointsService;
import com.huizu.project.service.ISysUserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: pjl
 * @Date: 2024/9/4
 * @ClassName: ApiTheoryScoreController
 * @Description: 理论成绩管理
 */
@Anonymous
@RestController
@RequestMapping("/project/theory/score")
public class TheoryScoreController extends BaseController {

    @Autowired
    private IProUserLlPointsService proUserLlPointsService;

    @Autowired
    private ISysUserAuthService  iSysUserAuthService;

    /**
     * 理论成绩列表
     * @param theoryScoreVo
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(TheoryScoreVo theoryScoreVo) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!SecurityUtils.isAdmin(user.getUserId())){
            SysUserAuth sysUserAuthPram = new SysUserAuth();
            sysUserAuthPram.setUserId(user.getUserId());
            List<SysUserAuth> auths = iSysUserAuthService.selectSysUserAuthList(sysUserAuthPram);
            List<String> bjs = auths.stream().filter(auth->auth.getType().equals("bj")).map(SysUserAuth::getBusId).collect(Collectors.toList());
            theoryScoreVo.setBjIds(bjs);
        }
        startPage();
        List<TheoryScoreVo> list = proUserLlPointsService.selectForList(theoryScoreVo);
        return getDataTable(list);
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> download() {
        try {
            // 指定文件路径
            Path filePath = Paths.get("/excel/scoreTemplate.xlsx");
//            Path filePath = Paths.get("/excel/scoreTemplate.xlsx");
            Resource resource = new UrlResource(filePath.toUri());

            // 确保文件存在
            if (resource.exists() || resource.isReadable()) {
                System.out.println("File found: " + resource.getFilename());
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                        .body(resource);
            } else {
                System.out.println("File not found or not readable: " + resource.getFilename());
                throw new RuntimeException("Could not read the file!");
            }
        } catch (MalformedURLException e) {
            System.out.println("Error while downloading file: " + e.getMessage());
            throw new RuntimeException("Error while downloading file", e);
        }
    }

    /**
     * 导入成绩
     * @param file
     * @return
     */
    @PostMapping("/importTheoryScore")
    public AjaxResult importTheoryScore(@RequestParam("file") MultipartFile file) throws Exception {
        proUserLlPointsService.importTheoryScore(file);
        return AjaxResult.success();
    }

    /**
     * 修改成绩
     * @param theoryScoreVo
     * @return
     */
    @PutMapping("/update")
    public AjaxResult update(@RequestBody TheoryScoreVo theoryScoreVo) throws Exception {
        proUserLlPointsService.update(theoryScoreVo);
        return AjaxResult.success();
    }


}
